<?php
namespace app\common\model;
use think\Exception;
use think\Model;
use think\Validate;

/**
 * 
 */
class Shop extends Model
{
	// 开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $rule =   [
        'sortid'    =>  'require',
        'name'        =>  'require|chsDash|length:2,30',
        'logo'       =>  'require',
        'content'       =>  'require|length:10,500',
        //'biz_url'    =>  'require',
    ];

    protected $msg  =   [
        'sortid.require'  =>  '请选择店铺类目',
        'name.require'    =>  '请输入店铺名称',
        'name.chsDash'     => '店铺名称不能含特殊字符',
        'name.length'      => '店铺名称长度为2-30个字符',
        'logo.require'     =>  '请上传门店logo',
        'content.require'  =>  '请输入店铺介绍内容',
        'content.length'    =>  '店铺介绍长度为10-500个字符',
        'biz_url.require'    => '请上传营业执照图片'
    ];
    /**
     * 浏览店铺
     */
    public function onViews($data=[]){
        try{
            $shopViews=ShopViews::where(['shop_id'=>$data['shop_id'],'uid'=>$data['uid']])->find();
            if(!$shopViews){#浏览
                $result=ShopViews::create([
                    'shop_id'=>$data['shop_id'],
                    'uid'=>$data['uid'],
                    'nums'=>1,
                    'ctime'=>time()
                ]);
                if(!$result){
                    return [false,'浏览记录写入失败'];
                }
                $this->where('id',$data['shop_id'])->setInc('views',1);
            }else{
                $shopViews->nums=['inc',1];
                $shopViews->utime=time();
                $result=$shopViews->save();
                if(!$result){
                    return [false,'浏览记录更新失败'];
                }
            }
            return [true,'success'];
        }catch (Exception $e){
            return [false,$e->getMessage()];
        }
    }
    /**
     * 收藏店铺
     */
    public function onFavs($data=[]){
        try{
            $shopFavs=ShopFavs::where(['shop_id'=>$data['shop_id'],'uid'=>$data['uid']])->find();
            if(!$shopFavs){#收藏
                $result=ShopFavs::create([
                    'shop_id'=>$data['shop_id'],
                    'uid'=>$data['uid'],
                    'status'=>1,
                    'ctime'=>time()
                ]);
                if(!$result){
                    return [false,'收藏失败'];
                }
                $this->where('id',$data['shop_id'])->setInc('favs',1);
            }else{
                if($shopFavs->status==1){#取消收藏
                    $shopFavs->status=0;
                    $shopFavs->utime=time();
                    $result=$shopFavs->save();
                    if(!$result){
                        return [false,'收藏失败'];
                    }
                    $this->where('id',$data['shop_id'])->setDec('favs',1);
                }else{#重新收藏
                    $shopFavs->status=1;
                    $shopFavs->utime=time();
                    $shopFavs->save();
                }
            }
            return [true,'success'];
        }catch (Exception $e){
            return [false,$e->getMessage()];
        }
    }
    /**
     * 店铺信息
     */
    public function shopInfo($data=[]){
        $shop=$this->with(['shopsort'])->where('id',$data['shop_id'])->find();
        if(!$shop){
            return [false,'获取失败'];
        }
        unset($shop['today_amount']);
        unset($shop['today_nums']);
        unset($shop['total_amount']);
        unset($shop['reason']);
        unset($shop['settle']);
        #查询是否收藏
        $is_favs=0;
        if($data['uid']==$shop['uid']){
            $is_favs=2;
        }else{
            $favs=ShopFavs::where(['shop_id'=>$data['shop_id'],'uid'=>$data['uid']])->find();
            if($favs && $favs->status==1){
                $is_favs=1;
            }
        }
        $shop['is_favs']=$is_favs;
        $shop['logo']=$shop['logo'].'_live';
        return [true,$shop];
    }
    /**
     * 获取店铺ID
     * @param int $uid 用户ID
     * @return int
     */
    public function getShopId($uid=0){
        $shop_id=$this->where('uid',$uid)->value('id');
        if(empty($shop_id)){
            $shop_id=0;
        }
        return $shop_id;
    }
    /**
     * 写入或更新店铺信息
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function setting($data=[]){
        try{
            $validate = new Validate($this->rule,$this->msg);
            if(!$validate->check($data)){
                return [false,$validate->getError()];
            }
            $shop=$this->where('uid',$data['uid'])->find();
            if($shop){
                $result=$shop->allowField(true)->save($data);
                if(!$result){
                    return [false,'店铺资料保存失败'];
                }
            }else{
                $data['ctime']=time();
                $result=$this->create($data,true);
                if(!$result){
                    return [false,'店铺资料设置错误'];
                }
                ShopPay::where(['uid'=>$data['uid']])->update(['shop_id'=>$result->id]);
            }
            return [true,'success'];
        }catch (Exception $e){
            return [false,$e->getMessage()];
        }
    }
    /**
     * 用户信息表关联
     * @return [type] [description]
     */
    public function user(){
    	return $this->hasOne(User::class,'id','uid');
    }
    /**
     * 类目表关联
     * @return [type] [description]
     */
    public function shopsort(){
    	return $this->hasOne(ShopSort::class,'id','sortid');
    }
    /**
     * 时间范围查询
     * @param  [type] $query [description]
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function searchCtimeAttr($query,$value, $data)
    {
        $start=$value[0]?strtotime($value[0]):0;
        $end=$value[1]?strtotime($value[1]):0;
        if(!empty($start)&&!empty($end)){
            $query->where('shop.ctime','between',[$start,$end]);
        }elseif(!empty($start)&&empty($end)){
            $query->where('shop.ctime','>',$start);
        }elseif(empty($start)&&!empty($end)){
            $query->where('shop.ctime','<',$end);
        }
    }
    /**
     * 状态查询
     * @param  [type] $query [description]
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function searchStatusAttr($query,$value, $data)
    {
        if(strlen($value)){
            $query->where('shop.status',$value);
        }       
    }
    /**
     * 关键字查询
     * @param  [type] $query [description]
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function searchNameAttr($query,$value, $data)
    {
        if(!empty($value)){
            $query->where('shop.uid|shop.name',$value);
        }
    }
}